package com.atguigu.flink0624.chapter08;

import com.atguigu.flink0624.bean.OrderEvent;
import com.atguigu.flink0624.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/16 15:43
 */
public class Flink06_Project_High_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new OrderEvent(Long.valueOf(data[0]),
                                      data[1],
                                      data[2],
                                      Long.parseLong(data[3]) * 1000);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((log, ts) -> log.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId)
            .window(EventTimeSessionWindows.withGap(Time.minutes(50)))
            .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {
                @Override
                public void process(Long key,
                                    Context ctx,
                                    Iterable<OrderEvent> elements,
                                    Collector<String> out) throws Exception {
                    List<OrderEvent> list = AtguiguUtil.toList(elements);
                    if (list.size() == 2) {
                        out.collect(key + " 正常交易....");
                    } else {
                        OrderEvent event = list.get(0);
                        if (event.getEventType().equals("create")) {
                            out.collect("订单: " + key + " 只有create没有pay, 或者pay超时支付");
                        } else {
                            out.collect("订单: " + key + " 只有pay没有create, 系统异常");
                        }
                    }
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
